<template>
  <div class="container">
    <avue-crud
      ref="avueRef"
      :option="option"
      :data="data"
      :page.sync="page"
      @search-change="searchchange"
      :before-close="beforeClose"
      @size-change="sizeChange"
      @current-change="currentChange"
      @row-save="rowSave"
      @row-update="rowUpdate"
    >
      <template #menu-right="{}">
        <el-button
          type="primary"
          size="small"
          icon="el-icon-plus"
          @click="rowAdd"
          >导入文件</el-button
        >
      </template>
      <template #address-form="row">
        <el-cascader
          style="width: 100%"
          v-model="formAddress"
          :options="optionsAddress"
          @change="handleChange"
          :props="propsAddress"
        />
      </template>
      <template #menu="{ row, index }">
        <el-button link type="primary" @click.stop="clickBtn(row, 1, index)"
          >入库</el-button
        >
        <el-button link type="primary" @click.stop="clickBtn(row, 2)"
          >删除</el-button
        >
      </template>
    </avue-crud>
    <el-dialog v-model="dialogVisible" title="文件导入" width="500">
      <el-form :model="dialogForm" label-width="auto" style="margin-top: 20px">
        <el-form-item label="文件上传">
          <el-upload
            ref="uploadRef"
            v-model:file-list="fileList"
            action="https://rq.hmx-cloud.com/file/upload"
            multiple
            :limit="1"
            :data="{ md5: Md5 }"
            :auto-upload="false"
            :on-change="ReadFileMD5"
            :on-success="onSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <el-button type="primary">点击上传</el-button>
            <template #tip>
              <div class="el-upload__tip">
                请上传xls、shp格式文件，文件大小限制10MB内.
              </div>
            </template>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="clickSave" :loading="loadingBtn">
            提交
          </el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog v-model="dialogVisible1" title="入库操作" width="900">
      <el-steps
        style="max-width: 600px"
        :active="stepsActive"
        finish-status="success"
      >
        <el-step title="数据类型" />
        <el-step title="标准选择" />
        <el-step title="字段匹配" />
      </el-steps>
      <el-form
        :model="dialogForm"
        label-width="auto"
        style="margin-top: 20px"
        v-if="stepsActive === 0"
      >
        <el-form-item label="数据类型">
          <el-select
            v-model="dialogForm.sheet"
            placeholder="请选择数据类型"
            size="large"
            style="width: 240px"
          >
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <el-table
        :data="tableData"
        border
        style="width: 100%"
        highlight-current-row
        v-if="stepsActive === 1"
        @current-change="handleCurrentChange"
        max-height="550"
      >
        <el-table-column type="index" label="序号" width="70" />
        <el-table-column prop="value" label="字段" />
      </el-table>
      <el-table
        :data="tableData1"
        border
        style="width: 100%"
        v-if="stepsActive === 2"
        max-height="550"
      >
        <el-table-column type="index" label="序号" width="70" />
        <el-table-column prop="comment" label="字段描述" width="160" />
        <el-table-column prop="fieldName" label="字段键值" width="160" />
        <el-table-column label="入库字段">
          <template #default="scope">
            <el-select
              v-model="scope.row.check"
              placeholder="请选择入库字段"
              size="large"
              style="width: 180px"
            >
              <el-option
                v-for="(item, index) in options1"
                :key="index"
                :label="item"
                :value="index"
              />
            </el-select>
          </template>
        </el-table-column>
      </el-table>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible1 = false">取消</el-button>
          <el-button type="primary" @click="clickSave1" :loading="loadingBtn">
            {{
              stepsActive === 0
                ? '下一步'
                : stepsActive === 1
                ? '下一步'
                : '提交'
            }}
          </el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog v-model="dialogVisible2" title="入库操作" width="900">
      <el-form :model="dialogForm" label-width="auto" style="margin-top: 20px">
        <el-form-item label="坐标系">
          <el-input
            v-model="dialogForm.crsCode"
            placeholder="请输入坐标系"
            style="width: 240px"
            size="large"
          ></el-input>
        </el-form-item>
        <el-form-item label="工程类型">
          <el-select
            v-model="dialogForm.gch"
            placeholder="请选择工程"
            style="width: 240px"
          >
            <el-option
              v-for="item in gcList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible2 = false">取消</el-button>
          <el-button type="primary" @click="clickSave2" :loading="loadingBtn">
            提交
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { onMounted, reactive, ref, toRefs } from 'vue'
import { ElMessage, ElMessageBox, formProps } from 'element-plus'
import { request } from '@/utils/request'
import * as row from './filelist.js'
import SparkMD5 from 'spark-md5'
const state = reactive({
  page: {
    size: 10,
    current: 1
  },
  total: 0,
  data: row.data,
  option: row.option,
  optionsAddress: [],
  propsAddress: {
    label: 'name',
    value: 'name'
  },
  formAddress: [],
  dialogVisible: false,
  dialogForm: {
    id: '',
    crsCode: '',
    gch: ''
  },
  fileList: [],
  Md5: '',
  loadingBtn: false,
  dialogVisible1: false,
  dialogVisible2: false,
  options: [],
  options1: [],
  stepsActive: 0,
  tableData: [],
  tableData1: [],
  currentRow: ''
})
const {
  data,
  page,
  option,
  optionsAddress,
  propsAddress,
  formAddress,
  dialogVisible,
  fileList,
  Md5,
  loadingBtn,
  dialogVisible1,
  dialogVisible2,
  options,
  options1,
  dialogForm,
  stepsActive,
  tableData,
  tableData1,
  currentRow
} = toRefs(state)
const beforeClose = (done) => {
  state.option = JSON.parse(JSON.stringify(row.option))
  done()
}
const handleCurrentChange = (val) => {
  currentRow.value = val
}
const uploadRef = ref(null)
const clickSave2 = () => {
  if (!dialogForm.value.crsCode) {
    ElMessage.error('请输入坐标系!')
    return
  }
  // if (!dialogForm.value.gch) {
  //   ElMessage.error('请选择工程!')
  //   return
  // }
  loadingBtn.value = true
  request({
    method: 'get',
    url: `/pop/excel_preview?id=${dialogForm.value.id}&crsCode=${dialogForm.value.crsCode}&gch=${dialogForm.value.gch}`
    // data: {
    //   ...dialogForm.value
    // }
  })
    .then((res) => {
      loadingBtn.value = false
      if (res.code === 200) {
        dialogVisible2.value = false
        ElMessage.success('文件入库成功!')
        initData()
      }
    })
    .catch((error) => {
      loadingBtn.value = false
      ElMessage.error('请稍后重试!')
    })
}
const clickSave1 = () => {
  if (stepsActive.value === 0) {
    if (!dialogForm.value.sheet) {
      ElMessage.error('请选择数据类型!')
      return
    }
    tableData.value = []
    request({
      method: 'get',
      url: '/file/analysisExcel',
      params: {
        ...dialogForm.value
      }
    }).then((res) => {
      if (res.code === 200) {
        res.data.forEach((item, index) => {
          tableData.value.push({
            index: index,
            value: Object.values(item).join(',')
          })
        })
        stepsActive.value = 1
        ElMessage.info('请选择第一行作为数据标准!')
      }
    })
  } else if (stepsActive.value === 1) {
    if (!currentRow.value) {
      ElMessage.error('请选择第一行作为数据标准!')
      return
    }
    tableData1.value = []
    request({
      method: 'get',
      url: '/pop/table_fields',
      params: {
        type: dialogForm.value.sheet === '管点' ? 'point' : 'line'
      }
    }).then((res) => {
      if (res.code === 200) {
        res.data.forEach((item) => {
          item.check = ''
        })
        tableData1.value = res.data
        options1.value = currentRow.value.value.split(',')
        options1.value.forEach((item, index) => {
          tableData1.value.forEach((item1) => {
            if (item1.comment === item) {
              item1.check = index
            }
          })
        })
        stepsActive.value = 2
      }
    })
  } else if (stepsActive.value === 2) {
    // console.log(tableData1.value)
    // console.log(currentRow.value.index)
    let status = 0
    tableData1.value.forEach((item) => {
      if (item.notNull && item.check === '') {
        status += 1
        ElMessage.error(`请先选择${item.comment}的入库匹配字段!`)
      }
    })
    if (status !== 0) {
      return
    }
    ElMessageBox.prompt(
      '请确认字段键值和入库字段匹配完成，请输入坐标系(如：4547)?',
      '温馨提示',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        inputPattern: /^(?!\s*$).+/,
        inputErrorMessage: '请输入坐标系'
      }
    ).then(({ value }) => {
      const obj = {}
      tableData1.value.forEach((item) => {
        obj[item.fieldName] = item.check
      })
      request({
        method: 'post',
        url: `/pop/excel_write_table_point?id=${dialogForm.value.id}&crsCode=${value}&sheet=${dialogForm.value.sheet}&head=4`,
        data: {
          ...obj
        }
      }).then((res) => {
        if (res.code === 200) {
          dialogVisible1.value = false
          ElMessage.success('文件入库成功!')
          initData()
        }
      })
    })
  }
}
const clickSave = () => {
  if (fileList.value.length === 0) {
    ElMessage.error('请先上传文件!')
    return
  }
  loadingBtn.value = true
  uploadRef.value.submit()
}
const ReadFileMD5 = async (param) => {
  const file = param.raw
  const sliceLength = 10
  const chunkSize = Math.ceil(file.size / sliceLength)
  const fileReader = new FileReader()
  const md5 = new SparkMD5()
  let index = 0
  const loadFile = () => {
    const slice = file.slice(index, index + chunkSize)
    fileReader.readAsBinaryString(slice)
  }
  loadFile()
  fileReader.onload = async (e) => {
    md5.appendBinary(e.target.result)
    if (index < file.size) {
      index += chunkSize
      loadFile()
    } else {
      // md5.end() 就是文件md5码
      Md5.value = md5.end()
      // const _data1 = await checkFileMd5(Md5.value)
      // if (_data1) {
      //   ElMessage.error('该文件已上传过，请选择其他文件!')
      //   Md5.value = ''
      //   fileList.value = []
      //   return
      // }
    }
  }
}
const beforeAvatarUpload = (rawFile) => {
  if (rawFile.size / 1024 / 1024 > 10) {
    ElMessage.error('文件大小请不要超过10M!')
    return false
  }
  return true
}
const onSuccess = (response) => {
  loadingBtn.value = false
  if (response.code === 200) {
    ElMessage.success('上传成功')
    dialogVisible.value = false
    initData()
  } else {
    ElMessage.error(response.msg)
    dialogVisible.value = false
  }
}
const avueRef = ref(null)
const searchchange = (row, done) => {
  state.page.current = 1
  if (row.likeName) {
    state.searchForm = {
      like: {
        username: row.likeName
      }
    }
  } else {
    state.searchForm = ''
  }
  initData()
  done()
}
//点击新增
const rowAdd = () => {
  fileList.value = []
  dialogVisible.value = true
  // getRegionTree()
  // postYz()
  // formAddress.value = []
  // avueRef.value.rowAdd()
}
//操作栏按钮
const clickBtn = (row, type, index) => {
  if (type === 1) {
    ElMessageBox.confirm('是否进行文件入库?', '温馨提示', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      dialogForm.value.id = row.id
      dialogForm.value.crsCode = ''
      dialogForm.value.gch = ''
      dialogVisible2.value = true
      // request({
      //   method: 'get',
      //   url: '/file/excelSheet',
      //   params: {
      //     id: row.id
      //   }
      // }).then((res) => {
      //   if (res.code === 200) {
      //     options.value = res.data.map((item) => {
      //       return { label: item, value: item }
      //     })
      //     stepsActive.value = 0
      //     tableData.value = []
      //     tableData1.value = []
      //     currentRow.value = ''
      //     dialogForm.value.sheet = ''
      //     dialogVisible1.value = true
      //   }
      // })
    })
  } else if (type === 2) {
    ElMessageBox.confirm('确认删除该条数据?', '温馨提示', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      request({
        url: '/file/del',
        method: 'get',
        params: {
          id: row.id
        }
      }).then((res) => {
        if (res.code == 200) {
          initData()
          ElMessage({
            message: '删除成功',
            type: 'success'
          })
        } else {
          ElMessage.error(res.msg)
        }
      })
    })
  }
}
//列表查询
const initData = async () => {
	const params = new URLSearchParams(sessionStorage.getItem('xzq'))
	// 将 URLSearchParams 转换为普通对象
	let obj = {}
	params.forEach((value, key) => {
	  obj[key] = value
	})
  request({
    method: 'post',
    url: '/file/page',
    data: {
      ...state.searchForm,
      ...state.page,
      query: {
        ...obj
      }
    }
  }).then((res) => {
    // res.data.records.forEach((item) => {
    //   item.address = (item.shen ?? '') + (item.shi ?? '') + (item.xie ?? '')
    // })
    state.data = res.data.records
    state.page.total = res.data.total
  })
}
//获取行政区划
const getRegionTree = () => {
  request({
    method: 'get',
    url: '/common/regionTree'
  }).then((res) => {
    optionsAddress.value = res.data
  })
}

//用户下级区划
const regionArr = ref([])
const getRegion = () => {
  request({
    method: 'get',
    url: '/common/user/region'
  }).then((res) => {
    const arr = res.data.map((item) => {
      return { label: item.name, value: item.name, rank: item.rank }
    })
    option.value.column[8].dicData = arr
    regionArr.value = arr
  })
}
//获取角色列表
const roleArr = ref([])
const getRole = () => {
  request({
    method: 'get',
    url: '/role/user/roles'
  }).then((res) => {
    const arr = res.data.map((item) => {
      return { label: item.roleName, value: item.id }
    })
    option.value.column[6].dicData = arr
    roleArr.value = arr
  })
}
//获取烟站列表
const postYz = () => {
  request({
    method: 'post',
    url: '/yz/page',
    data: {
      size: 9999,
      current: 1
    }
  }).then((res) => {
    state.option.column[10].dicData = res.data.records.map((item) => {
      return { label: item.name, value: item.name }
    })
  })
}
//编辑保存
const rowUpdate = (row, index, done, loading) => {
  if (formAddress.value.length === 0) {
    ElMessage({
      message: '请先选择行政区划',
      type: 'error'
    })
    loading()
    return
  }
  delete row.likeName
  row.shen = formAddress.value[0]
  row.shi = formAddress.value[1]
  row.xie = formAddress.value[2]
  request({
    method: 'post',
    url: '/user/yn/update',
    data: {
      ...row
    }
  })
    .then((res) => {
      loading()
      if (res.code === 200) {
        ElMessage({
          message: '修改成功',
          type: 'success'
        })
        done()
        initData()
      } else {
        ElMessage(res.msg)
      }
    })
    .catch((error) => {
      console.log(error)
      loading()
    })
}
//新增保存
const rowSave = (form, done, loading) => {
  delete form.id
  delete form.likeName
  const result = roleArr.value.find((item) => item.value === form.role)
  if (result) {
    form.roleName = result.label
  }
  let type = ''
  if (regionArr.value.length > 0) {
    type = regionArr.value[0].rank
  }
  if (type === 1) {
    form.shen = form.xzqh
  } else if (type === 2) {
    form.shi = form.xzqh
  } else if (type === 3) {
    form.xie = form.xzqh
  }
  delete form.xzqh
  request({
    method: 'post',
    url: '/user/yn/addUser',
    data: {
      ...form
    }
  })
    .then((res) => {
      loading()
      if (res.code === 200) {
        ElMessage({
          message: '新增成功',
          type: 'success'
        })
        done()
        initData()
      } else {
        ElMessage(res.msg)
      }
    })
    .catch((error) => {
      console.log(error)
      loading()
    })
}
//分页查询--条数
const sizeChange = (val) => {
  page.value.size = val
  page.value.current = 1
  initData()
}
//分页查询--页码
const currentChange = (val) => {
  page.value.current = val
  initData()
}
const gcList = ref([])
const getApi = () => {
  request({
    url: '/engineering/page',
    method: 'post',
    data: {}
  }).then((res) => {
    if (res.code == 200) {
      // res.data.records.forEach((item) => {
      //   item.text = `${item.name}-${item.shi}-${item.xian}`
      // })
      const list = res.data.records.map((item) => {
        return {
          value: item.gch,
          label: `${item.name}-${item.shi}-${item.xian}`
        }
      })

      gcList.value = list
    } else {
      ElMessage.error(res.msg)
    }
  })
}
onMounted(() => {
  initData()
  getApi()
  // 获取URL中的片段标识符部分（包括#）
  const hashString = window.location.hash // 例如: '#代理=湖南省&shi=长沙市&xian=岳麓区'

  // 如果片段标识符不为空，则处理它
  if (hashString) {
    // 移除#字符，然后使用URLSearchParams进行解析
    const paramsString = hashString.slice(1) // 去除开头的#
    // 输出结果
    sessionStorage.setItem('xzq', paramsString.split('?')[1])
  }
  // getRole()
  // getRegion()
})
</script>

<style lang="scss" scoped>
.container {
  background-color: #fff;
  padding: 20px;
  border-radius: 10px;
}

:deep(div.el-table__body-wrapper) {
  height: calc(100vh - 260px);
  flex: none;
}

.avue-crud__pagination .el-pagination {
  margin-right: 10px;
}

:deep(.el-card) {
  border-radius: 0;
}

:deep(.el-select--large .el-select__wrapper) {
  min-height: 26px;
  padding: 2px 16px;
}

:deep(.el-table--large .el-table__cell) {
  padding: 6px 0;
}
</style>
